﻿#include "ScriptInstructionFactory.h"

#include "ScriptInstruction.h"

ScriptInstructionFactory::ScriptInstructionFactory()
{
}

ScriptInstructionFactory::~ScriptInstructionFactory()
{}

QList<ScriptInstruction*> ScriptInstructionFactory::fromByteArray(QByteArray data)
{
  QList<ScriptInstruction*> script;
  char* src=data.data();
  int size=data.size();
  int offset=0;
  uint deviceId=*(uint*)src;
  offset+=sizeof (deviceId);
  ScriptInstruction* scriptInstruction=Q_NULLPTR;
  while (true)
    {
      scriptInstruction=ScriptInstruction::fromByteArray(src,size,&offset);
      if(Q_NULLPTR==scriptInstruction)
        {
          break;
        }
      script.append(scriptInstruction);
    }
  for(ScriptInstruction* scriptInstruction:script)
    {
      scriptInstruction->setDeviceId(deviceId);
    }
  return script;
}

QByteArray ScriptInstructionFactory::scriptToByteArray(QList<ScriptInstruction*> script)
{
  uint deviceId=script.first()->getDeviceId();
  QByteArray data;
  data.append((char*)&deviceId,sizeof (deviceId));
  for(ScriptInstruction* scriptInstruction:script)
    {
      data.append(scriptInstruction->toByteArray());
    }
  return data;
}
